#pragma 
#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<cerrno>
#include<fcntl.h>
using namespace std;
#define Size 256
const string Path = "./myfifo";
#define creater 1
#define user 2
class NamedPipe
{
public:
    NamedPipe(const string &Path,int id) :path(Path),id(id)
    {
        if(id==creater)
        {
            int ret = mkfifo(path.c_str(), 0666);
            cout << ret << endl;
            if (ret != 0)
            {
                perror("mkfifo");
            }
        }
        openNamedPipe();
    }
    int removeNamedpipe()
    {
        int ret = unlink(path.c_str());
        if(ret!=0)
        {
            perror("mkfifo");
        }
        return ret;
    }

    ~NamedPipe()
    {
        if(id==creater)
        removeNamedpipe();
    }
    int Read(string* out)
    {
        char buffer[Size];
        int n = read(fd, buffer, Size);
        if(n>0)
        {
            buffer[Size] = 0;
            *out = buffer;
        }
        return n;
    }
    void Write(const string& in)
    {
        write(fd, in.c_str(), in.size());
    }

private : 
    const string path;
    int id;
    int fd;
    int openNamedPipe()
    {
        cout << path << endl;
        if (id == creater)
            fd = open(path.c_str(), O_RDONLY);
        else
          fd = open(path.c_str(), O_WRONLY);
      
        return fd;
    }
};
